(function(){
	//设置命名空间
	var CodeSTD = window.CodeSTD || {};
	window.CodeSTD = CodeSTD; 
	/**
	 * 创建Form表单
	 * @author 王成委
	 * @param config Object
	 *  <p>url:form的Action，提交的后台地址</p>
	 *  <p>method:使用POST还是GET提交表单</p>
	 *  <p>params:参数 K-V</p>
	 * @return Form
	 */
	CodeSTD.form = function(config){
		config = config || {};
		var url = config.url,
		method = config.method || 'GET',
		params = config.params || {};
		var form = document.createElement('form');
		form.action = url;
		form.method = method;
		//form.target = "_blank";
		for(var param in params){
			var value = params[param],
			input = document.createElement('input');
			input.type = 'hidden';
			input.name = param;
			input.value = value;
			form.appendChild(input);
		}
		return form;
	}
})()
$(function () {
        	/* $(".m_goback").on("click",function(){
        		 if(confirm("确定离开本页面？")){
        		 	document.location.href = 'javascript:history.go(-1)';
        		 }
        	})  */
        	//微信左上角返回键
            /* pushHistory(); 
            window.addEventListener("popstate", function(e) { 
                //alert("我监听到了浏览器的返回按钮事件啦");
                if(confirm("确认返回吗？")){
                	document.location.href = "#";
                }else{
                    pushHistory();
                }
            }, false); 
            function pushHistory() { 
                var state = { 
                    title: "title", 
                    url: "Shop/QuickCart"
                }; 
                window.history.pushState(state, "title", "Shop/QuickCart"); 
            } */
            
            
        	var count=$(".c_checked").length;
        	$(".m_sub_btn").val("结算("+count+")");
        	//alert(count);
            totalM();
           
		 //单个选择
        $(".m_prd_d table span.p_ck_one:visible").live("click",function () {
            $(this).hasClass("c_checked") ? $(this).removeClass("c_checked") : $(this).addClass("c_checked");
            check();
            totalM();
        })
            //点击图片触发单选
		$(".m_prd_d table .pic:visible").live("click",function(){
			$(this).parents("table").find(".p_ck_one").trigger("click");
		})
        //全选择
        $(".m_all_b span.car_ck_all").live("click",function () {
            $(this).hasClass("c_checked") ? $(".m_qx:visible").removeClass("c_checked") : $(".m_qx:visible").addClass("c_checked");
            var count=$(".c_checked:visible").length-1<0?0:$(".c_checked:visible").length-1;
        	$(".m_sub_btn").val("结算("+count+")");
            totalM();
        })

        //增加
        $(".m_ps").live("click", function () {
            //var id = $(this).parents(".m_c_tab").find(".m_qx").attr("tid");
        	var th = $(this).parents(".m_c_tab");
            var minnum = parseInt(th.find("#minnum").val());
            var input=$(this).prev(".m_dl_sl")
            var t = parseInt(input.val());
            t += minnum;
            input.val(t);
          	//数量超出限购
            //小于1000的中包装量最大倍数
            var maxnum=1000-1000%minnum;
			if(t>maxnum){
				input.testRemind("不能超出限购数量!").val(maxnum);
			}
            var $this=$(this);
            changePrice($this);
            totalM();
        })

        //减少
        $(".m_pp").live("click", function () {
        	var th = $(this).parents(".m_c_tab");
            var minnum = parseInt(th.find("#minnum").val());
            var t = parseInt($(this).next(".m_dl_sl").val());
            if (t > minnum) {
                t = t - minnum;
                $(this).next(".m_dl_sl").val(t);
                var nums = $(this).next(".m_dl_sl").val();
            }
            else {
                t = minnum;
            }
            var $this=$(this);
            changePrice($this);
            totalM();
        })

        $(".m_dl_sl").live("blur",function () {
            var th = $(this).parents(".m_c_tab");
            var minnum = parseInt(th.find("#minnum").val());
            var t = $(this);
          	//判断非数字、非整数、空
            var re=/^\d+$/;
            if(isNaN(t.val())||!re.test(t.val())||t.val()=="")t.val(minnum);
            //数量超出限购
            //小于1000的中包装量最大倍数
            var maxnum=1000-1000%minnum;
			if(t.val()>maxnum){
				t.testRemind("不能超出限购数量!").val(maxnum);
			}else{
                var tt = parseInt(t.val());
				if(tt==0)t.val(minnum);
                if (tt % minnum != 0) {
                    var tmp = tt - tt % minnum + minnum;
                    if (tmp < minnum) {
                        tmp = minnum;
                    }
                    t.val(tmp);
                }
			}
			var $this=$(this);
            changePrice($this);
            totalM();
        });

        //提交
        $(".m_sub_btn").on("click",function () {
        	var count=$(".c_checked").length;
        	var search=$(".m_prd_d .m_c_tab:visible").length;
        	if(count==0||search==0){
        		//alert("您没有选择任何商品！");
        		$("#count").testRemind("您没有选择任何商品！");
        		return false;
        	}
            var spids = new Array();
            var nums = new Array();
            var tag=true;
            $(".m_prd_d .m_c_tab:visible").each(function () {//循环，逐个判断商品是否超出限购数量
                if ($(this).find("span.p_ck_one").hasClass("c_checked")) {
                	var minnum = $(this).find("#minnum").val();
               		var maxnum=1000-1000%minnum;
               		var input=$(this).find(".m_dl_sl");
               		var stock=$(this).find("#stock").val();
                	//判断商品批号是否为空
                	var pihao=$(this).find('.pihao').html().trim()
               		if(pihao==''||pihao=='库存不足'||parseInt(input.val())>stock){
               			var spmch=$(this).find('.m_p_name').html();//查找对应的商品名称
               			$(".m_sub_btn").testRemind(spmch+'库存不足！');
               			tag=false;
               			return false;//跳出循环
               		}
               		//判断商品是否超出限购数量
               		if(parseInt(input.val())>maxnum){
               			input.focus().testRemind("不能超出限购数量!").val(maxnum);
                          totalM();
                          tag= false;//如果有超过限购数量
                          return false;//跳出循环
               		}
                    var spid = $(this).find(".m_qx").attr("tid");
                    var num=input.val();
                    spids.push(spid);
                    nums.push(num);
                }
            });
            if(!tag)return false;//阻止提交
            var spidarray = spids.join(",");
            var numarray = nums.join(",");
            //window.location.href = "Shop/QuickOrder";
            var form = new CodeSTD.form({
		        url:'Shop/QuickOrder',
		        method:'POST',
		        params:{
		        	spidarray:spidarray,
		        	numarray:numarray,
		        	sjid:sjid
		        }
		    })
		    $(form).submit();
		    form = null;
        })
    })
    
    //搜索商品 
	   $("#prosearch").on("input",function(){
		   //alert($(this).val())
    	   $(".m_c_tab").show();
    	   //$(".m_maddmore").show();
    	   console.log(initsize);
    	   $(".m_c_tab:gt("+(initsize-1)+")").remove();
		   $(".m_all_b").show();
		   var search=$(this).val();
		   if(search!=null&&search.trim()!=""){
		   		//$(".m_prd_d").empty();
    		   	$(".m_c_tab").hide();
    		   	//$(".m_maddmore").hide();
    		   	$(".m_sub_btn").val("结算(0)");
    		   	$(".m_a_prie").html("￥0.00")
    		    $(".m_all_b span.car_ck_all").removeClass("c_checked"); 
    		   	//$(".m_c_tab").find(".c_checked").hide();
    		   	//$(".m_all_b").hide();
    		   $.ajax({
                   url: "Shop/Search",
                   data: {search:search,sjid:sjid},
                   type: "post",
                   success: function (data) {
                	   if(data.length>0){
	                	   $.each(data,function(i,v){
	                		   if(v.pihao==null)v.pihao='库存不足';
	                		   var table = 
	                		"<table class='m_c_tab'>"
	                          +"<tbody>"
	                               +"<tr>"
	                                   +"<td rowspan='2' align='left' valign='top' width='10%'>"
	                                       +"<span class='m_qx p_ck_one p_ck_one130083' tid="+v.spid+"></span>"
	                                       +"<input id='minnum' value='"+v.zhongbz+"' hidden />"
	                                       +"<input id='priceZhj' value='"+v.price+"' hidden />"
	                                       +"<input id='priceChl' value='"+v.priceChl+"' hidden />"
	                                       +"<input id='jlgg' value='"+v.jlgg+"' hidden />"
	                                       +"<input id='stock' value='"+v.productBal[0].kxshl+"' hidden />"
	                                     +"</td>"
	                                 +"<td rowspan='2' class='pic'>"
	                                  + "<a class='m_p_plink touri' href='javascript:;'>"
	                                   //+"<img src='images/product/"+v.spid+"/0.jpg' height='88px' width='90px'/>"    
	                                   +"<img src='http://www.hnhcyy.com/resource/img/"+v.spid+"/10.jpg' height='88px' width='90px'/>"    
	                                   +"</a>"
	                               +"</td>"
	                               +"<td class='relative'>"
	                               	if(v.zengsong!=null){
	                               		table+="<span class='gift'>礼</span>"
	               					}
                               		table+="<a href='Shop/Detail?productid="+v.spid+"&&sjid="+sjid+"' style='width: 170px;' class='m_p_name escp'>"+v.spmch+"</a>"
                               		+"<span id='zjg' class='f60 p_dg_jg'>￥<span class='price'>";
                               		if(v.priceChl!=0&&v.priceChl!=null){
                               			table+=v.priceChl;
                               		}else{
                               			table+=v.price
                               		}
	                		   		table+="</span></span>"
	                               		+"<span class='m_p_cmbz'>" 
	                               		+"<span class='m_p_cm2' style='font-size:11px;'>批号：≥<em class='pihao' style='font-style:initial;'>"+v.pihao+"</em></span>"  
	                               		+"<span class='lingshoujia'>￥"+v.lingshoujia+"</span>"
	                               		+"</span>" 
										+"<span class='guige'>规格："+v.shpgg
										+"</span>"
	                               +"</td>"
	                               +"</tr>"
	                           //实现加减
	                           +"<tr>"
	                           +"<td align='left' valign='middle'>"
	                           +" <span class='m_p_pts'>"
	                           +" <div style='color:#999999' class='m_pp bbox icon-reduce'></div>"
	                           +"<input class='m_dl_sl bbox' maxlength='4' value="+v.zhongbz+" type='text'>"
	                           +"<div class='m_ps bbox icon-add'></div>"
	                           +"<input class='m_dl_addcar m_dl_addcar2' value='加入购物车' type='button'>"
	                           +"</span></td>"
	                           +"</tr>"
	                           +"</tbody>"
	                       +"</table>" 
	                       $(".m_prd_d").append(table);
	                     //价格小数点后如果是1位就转换成2位
	                       $(".price,.lingshoujia").each(function(){
	                    	   setScale($(this));
	                       });
	           			});
	                	  $("#loading").hide();
	                  }else{
	                	  $(".m_all_b,#loading").hide();
	                  }
                   }
               });
		   }else{
			   $("#loading").show();
                check();
                totalM();
		   }
	   });
		//加入购物车
		//var cartNum=0;
        $(".m_dl_addcar").live("click",function () {
        	//批号为空
        	var $this = $(this);
        	var mctab = $this.parents('.m_c_tab');
        	var pihao = mctab.find('.pihao').html().trim();
        	var stock = mctab.find("#stock").val();
        	var ordernum = parseInt(mctab.find(".m_dl_sl").val());
        	if(pihao=="库存不足"||ordernum>stock){
        		$this.testRemind("库存不足！");
        		return;
        	}
        	var minnum = mctab.find("#minnum").val();
        	var maxnum = 1000-1000%minnum;
            if(ordernum <= maxnum){
	            var productid = mctab.find(".m_qx").attr("tid");
	            var msg = "";
	            if(productid=="SPH00001954")msg="购买60盒，赠送衬衫一件";
	             $.ajax({
	                 url: 'Shop/Cart/AddCart',
	                 data: {spid: productid, FQty: ordernum,sjid:sjid},
	                 type: 'post',
	                 success: function (data) {
	                	 if(data){
	                		 $this.testRemind("成功加入购物车！"+msg)
	                		 //cartNum += parseInt(ordernum);
	                		 //$(".cart_i_p").text(cartNum).removeClass("none_im");
	                	 }else{
	                		 $this.testRemind("加入购物车失败！")
	                	 }
	                 }
	             }); 
            }else{
            	mctab.find(".m_dl_sl").testRemind("超出限购数量!");                                                      
            }
         }); 
        
        //价格小数点后如果是1位就转换成2位
        $(".price,.lingshoujia").each(function(){
        	setScale($(this))
        })